import React, { ReactElement } from 'react'
import { Menu } from 'antd'
import { Link } from 'react-router-dom'
import Icon from '@/components/Icon'
import { IRoute } from '@/interface/router'

const { SubMenu } = Menu

const getMenuTree = (routers: IRoute[]) => {
  return routers.reduce((pre: ReactElement[], item: IRoute) => {
    if (item.hidden) {
      return pre
    }
    const isChild = item.children && item.children.filter((routeItem) => !routeItem.hidden).length > 0
    if (!isChild) {
      pre.push(
        <Menu.Item key={item.key} icon={<Icon type={item.icon} />}>
          <Link to={{ pathname: item.path }} target={item.path.startsWith('http') ? '_blank' : '_self'}>
            <span>{item.title}</span>
          </Link>
        </Menu.Item>,
      )
    } else {
      !item.hidden && pre.push(
        <SubMenu key={item.key} title={item.title} icon={<Icon type={item.icon} />}>
          {getMenuTree(item.children)}
        </SubMenu>,
      )
    }

    return pre
  }, [])
}
export default getMenuTree
